import 'dart:convert';

import 'package:android_intent_plus/android_intent.dart';
import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sph_shipper/http/getapi.dart';
import 'package:url_launcher/url_launcher.dart';

import '../AppConfig/Config.dart';
import '../AppConfig/LocalStorage.dart';
import '../AppConfig/RouteAct.dart';
import '../AppConfig/ShowDialog.dart';
import '../AppConfig/StringEncapsulation.dart';
import '../FandCar/DriverIntroduction.dart';
import '../FandCar/SelectSourceOfGoods.dart';
import '../http/api.dart';
import '../l10n/messages.dart';
import 'package:platform/platform.dart';
import '../http/NoLoadingGetApi.dart';
class MatureCarList extends StatefulWidget {
  const MatureCarList({super.key, required this.orderId, required this.shipperId});
  final String orderId;
  final String shipperId;

  @override
  State<MatureCarList> createState() => _MatureCarListState();
}

class _MatureCarListState extends State<MatureCarList> {
List dataList=[];
int pageNum=1;
String searchPhone="";
String searchVel="";
  FocusNode focusNode = FocusNode();
  BrnSearchTextController scontroller = BrnSearchTextController();
  TextEditingController textController = TextEditingController();

  @override
  void initState() {
    textController.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
          scontroller.isActionShow = true;
        }
      }
    });
    focusNode.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
        }
      }
    });

    getMyDriversAction("","");

    super.initState();
  }

  _makePhoneCall(String phoneNumber) async {
    if (LocalPlatform().isAndroid) {
      var status = await Permission.phone.status;
      if (status.isGranted) {
        // 权限已被授予
        // callPhone();
        final AndroidIntent intent = AndroidIntent(
          action: 'android.intent.action.CALL',
          data: Uri.encodeFull('tel:$phoneNumber'),
        );
        await intent.launch();
      } else if (status.isDenied) {
        // 权限被拒绝，但用户可以再次授权
        showCallPhoneFirstDialog(context);
        status = await Permission.phone.request();
        if (status.isGranted) {
          // 用户同意了权限
          // callPhone();
          final AndroidIntent intent = AndroidIntent(
            action: 'android.intent.action.CALL',
            data: Uri.encodeFull('tel:$phoneNumber'),
          );
          await intent.launch();
        } else {
          showCallPhoneDialog(context);
          // 用户拒绝权限，无法发起电话
          // 可以在此处展示信息提示用户需要权限
        }
      } else if (status.isPermanentlyDenied) {
        // 权限被永久拒绝，需要用户手动开启权限
        showCallPhoneDialog(context);
      }

    }else{
      final url =Uri.parse('tel:$phoneNumber');
      if (await canLaunchUrl(url)) {
        await launchUrl(url);
      } else {
        throw '无法拨打电话：$url';
      }
    }
  }

void getMyDriversAction(String phoneNum,String vehicleNum) async {
  String? ShipperId = await UserIdManager.getUserID();
  NoLoadinggetApiManager.getData(
    context, // 上下文对象，用于显示提示信息等
    'api/auth/shipper/driver/page', // 您的API端点
    {"shipperId":ShipperId,"current":pageNum,"size":20,"phoneNum":searchPhone,"vehicleNum":searchVel}, // 查询参数，如果没有可以传递null
        (responseData)  {
      setState(() {
        if(pageNum==1) {
          dataList = responseData['data']['records'];
        }else{
          if(responseData['data']['records'].isNotEmpty){
            dataList.addAll(responseData['data']['records']);
          }else{
            pageNum=pageNum-1;
          }
        }
      });

    },
  );
}

void _onRefresh(){
  pageNum=1;
  getMyDriversAction("","");
}
void _loadMoreData(){
  if(dataList.length>20*pageNum-1){
    pageNum=pageNum+1;
    getMyDriversAction("","");
  }

}

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        leading: IconButton(icon: Icon(Icons.arrow_back_ios,color: Colors.black,),onPressed: (){Navigator.pop(context);},),
        centerTitle: true,
        backgroundColor: Colors.white,
        title: Text("熟车列表",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w300),),
      ),
      body: ListView(
        children: [
          BrnSearchText(
            focusNode: focusNode,
            controller: textController,
            searchController: scontroller..isActionShow = false,
            outSideColor:MyColors.backgreyColor,
            innerColor:Colors.white,
            borderRadius:BorderRadius.all(const Radius.circular(10.0)),
            hintText:"输入司机手机号码/车牌号",
            onTextClear: () {
              debugPrint('sss');
              return false;
            },
            autoFocus: false,
            onActionTap: () {
              scontroller.isClearShow = false;
              scontroller.isActionShow = false;
              focusNode.unfocus();
              BrnToast.show('取消', context);
            },
            onTextCommit: (text) {

            },
            onTextChange: (text) {
              if (text.contains(RegExp(r'[a-zA-Z]')) && text.length > 0) {
                setState(() {
                  searchVel=text;
                });

                getMyDriversAction("",text);
              } else {
                setState(() {
                  searchPhone=text;
                });
                getMyDriversAction(text, "");
              }

            },
          ),
          Container(

              color: Colors.white,
              height: screenSize.height-220.h,
              child:EasyRefresh(
                  header:  ClassicHeader(
                    dragText: '下拉刷新',
                    armedText: '准备释放',
                    readyText: '加载中...',
                    processingText: '加载中...',
                    processedText: '刷新成功',
                    noMoreText: '暂无更多',
                    failedText: '刷新失败',
                    messageText: '刷新时间 %T',
                  ),

                  footer: ClassicFooter(
                    dragText: '加载更多',
                    armedText: '准备释放',
                    readyText: '加载中...',
                    processingText: '加载中...',
                    processedText: '加载成功',
                    noMoreText: '暂无更多',
                    failedText: '加载失败',
                    messageText: '加载时间 %T',
                  ),
                  onRefresh: _onRefresh,
                  onLoad: dataList.length > 20*pageNum-1?_loadMoreData:null,
                  child:
                  ListView(
                    children: [
                      dataList.length==0?BrnAbnormalStateWidget(
                        img: Image.asset(
                          'lib/Images/OrderList/发货中暂无货源.png',
                          scale: 3.0,
                        ),
                        content: '暂无熟车',

                      ):Container(
                        height: screenSize.height-220.h,
                        color: MyColors.backgreyColor,
                        child: ListView.builder(
                            shrinkWrap:false,
                            itemCount:dataList.length,
                            itemBuilder: (BuildContext context, int index) {
                              return GestureDetector(
                                child:    Container(
                                  decoration: BoxDecoration(
                                      color:Colors.white,
                                      borderRadius: BorderRadius.all(Radius.circular(10))),
                                  margin: EdgeInsets.only(left: 10.w,right: 10.w,bottom: 8.h),
                                  padding: EdgeInsets.only(left:15.w,right: 15.w,top: 10.h,bottom: 10.h),
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          Row(
                                            children: [
                                              Container(
                                                decoration: BoxDecoration(
                                                    color: Colors.white,
                                                    borderRadius: BorderRadius.all(Radius.circular(10))),
                                                child: ClipRRect(
                                                  borderRadius: BorderRadius.all(Radius.circular(10)),
                                                  child: dataList[index]['avatarPath']!=""&&dataList[index]['avatarPath']!=null?Image.network(
                                                    MyServiceUrl.imgHeader + dataList[index]['avatarPath'],
                                                    width: 36.w,
                                                    height: 36.h,
                                                    fit: BoxFit.cover,
                                                  ):Image.asset("lib/Images/login/默认头像.jpeg",width: 36.w, height: 36.h, fit: BoxFit.cover,),
                                                ),
                                              ),
                                              SizedBox(width: 8.w,),
                                              if(dataList[index]['realName']!=null)
                                                Column(
                                                  crossAxisAlignment: CrossAxisAlignment.start,
                                                  children: [
                                                    Text(dataList[index]['realName'],style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                                                    Text(maskPhoneNumber(dataList[index]['phoneNum']),style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                                                  ],
                                                ),

                                            ],
                                          ),
                                          Column(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              Row(
                                                children: [
                                                  Text("身份认证",style: TextStyle(fontSize: 10.sp,color: MyColors.authTipColor,),),
                                                  (dataList[index]['personalStatus']==0||dataList[index]['personalStatus']==3)?

                                                  Icon(Icons.
                                                  error_outline,color: Colors.red,size: 15,)
                                                      :dataList[index]['personalStatus']==1?

                                                  Icon(Icons.access_time,color: MyColors.themeColor,size: 12,)
                                                      :
                                                  Icon(Icons.check_circle_outline,color: Colors.green,size: 12,),

                                                  Text("驾驶证",style: TextStyle(fontSize: 10.sp,color: MyColors.authTipColor,),),
                                                  (dataList[index]['driverLicenseStatus']==0||dataList[index]['driverLicenseStatusdriverLicenseStatus']==3)?

                                                  Icon(Icons.
                                                  error_outline,color: Colors.red,size: 12,)
                                                      :dataList[index]['driverLicenseStatus']==1?

                                                  Icon(Icons.access_time,color: MyColors.themeColor,size: 12,)
                                                      :
                                                  Icon(Icons.check_circle_outline,color: Colors.green,size: 12,),


                                                  Text("从业资格证",style: TextStyle(fontSize: 10.sp,color: MyColors.authTipColor,),),
                                                  (dataList[index]['vehicleDrivingLicenseStatus']==0||dataList[index]['vehicleDrivingLicenseStatus']==3)?

                                                  Icon(Icons.
                                                  error_outline,color: Colors.red,size: 12,)
                                                      :dataList[index]['vehicleDrivingLicenseStatus']==1?

                                                  Icon(Icons.access_time,color: MyColors.themeColor,size: 12,)
                                                      :
                                                  Icon(Icons.check_circle_outline,color: Colors.green,size: 12,),


                                                ],
                                              ),
                                              Row(
                                                children: [
                                                  Text("道路运输证",style: TextStyle(fontSize: 10.sp,color: MyColors.authTipColor,),),
                                                  (dataList[index]['roadTransportCertificateStatus']==0||dataList[index]['roadTransportCertificateStatus']==3)?

                                                  Icon(Icons.
                                                  error_outline,color: Colors.red,size: 15,)
                                                      :dataList[index]['roadTransportCertificateStatus']==1?

                                                  Icon(Icons.access_time,color: MyColors.themeColor,size: 12,)
                                                      :
                                                  Icon(Icons.check_circle_outline,color: Colors.green,size: 12,),
                                                  Text("从业资格证",style: TextStyle(fontSize: 10.sp,color: MyColors.authTipColor,),),
                                                  (dataList[index]['qualificationCertificateStatus']==0||dataList[index]['qualificationCertificateStatus']==3)?

                                                  Icon(Icons.
                                                  error_outline,color: Colors.red,size: 12,)
                                                      :dataList[index]['qualificationCertificateStatus']==1?

                                                  Icon(Icons.access_time,color: MyColors.themeColor,size: 12,)
                                                      :
                                                  Icon(Icons.check_circle_outline,color: Colors.green,size: 12,),


                                                ],
                                              ),
                                            ],
                                          ),

                                        ],
                                      ),
                                      SizedBox(height: 4.h,),
                                      Text(dataList[index]['vehicleNum']!=null?dataList[index]['vehicleNum']:"",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                                      SizedBox(height: 4.h,),
                                      Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          if(dataList[index]['vehicleLength']!=null)
                                            Row(
                                              children: [
                                                Text(dataList[index]['vehicleLength']+"丨"+dataList[index]['vehicleModel']+"丨"+dataList[index]['vehicleTonnage']+"吨",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),)
                                              ],
                                            ),
                                          // RichText(
                                          //   text: TextSpan(
                                          //     text: '好评率 ', // 第一部分文本
                                          //     style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),
                                          //     children: [
                                          //       TextSpan(
                                          //         text: dataList[index]['driverReview']!=null?'100%':"暂无评价", // 第二部分文本
                                          //         style: TextStyle(color: MyColors.themeColor,fontSize: 13.sp),
                                          //       ),
                                          //     ],
                                          //   ),
                                          // ),
                                        ],
                                      ),
                                      Divider(
                                        height: 10.h,
                                        color: MyColors.backgreyColor,
                                      ),
                                      Container(
                                        height:30.h,
                                        child:  Row(
                                          mainAxisAlignment: MainAxisAlignment.end,
                                          children: [
                                            GestureDetector(
                                              child:  BrnTagCustom.buildBorderTag(
                                                tagText: '指定承运',
                                                textColor: MyColors.themeColor,
                                                borderColor: MyColors.themeColor,
                                                fontWeight: FontWeight.w600,
                                                borderWidth: 1,
                                                fontSize: 12.sp,
                                                tagBorderRadius:BorderRadius.all(Radius.circular(30)),
                                                textPadding: EdgeInsets.all(6),
                                              ),
                                              onTap: (){
                                                Navigator.push( context, FadeRoute(page:SelectSourceOfGoods(carMap:dataList[index],)));
                                              },
                                            ),
                                            SizedBox(width: 8.w,),
                                            GestureDetector(
                                              child:  BrnTagCustom.buildBorderTag(
                                                tagText: '电话联系',
                                                textColor: MyColors.themeColor,
                                                borderColor: MyColors.themeColor,
                                                fontWeight: FontWeight.w600,
                                                borderWidth: 1,
                                                fontSize: 12.sp,
                                                tagBorderRadius:BorderRadius.all(Radius.circular(30)),
                                                textPadding: EdgeInsets.all(6),
                                              ),
                                              onTap: (){
                                                _makePhoneCall(dataList[index]['phoneNum']);
                                              },
                                            ),
                                          ],
                                        ),
                                      ),

                                    ],
                                  ),
                                ),
                                onTap: (){
                                  Navigator.push( context, FadeRoute(page:DriverIntroduction(DrvId: dataList[index]['driverId'],)));
                                },
                              );

                            }
                        ),
                      )


                    ],
                  )
              )
          )
        ],
      ),
    );
  }
}
